<template>
  <base-modal class="fault-library-dialog" :title="$t('component.faultLibraryDialog.choosePlaceholder')" width="600px" :show.sync="isShow">
    <div class="fault-library_wrap">
        <!-- 搜索栏 -->
      <div class="fault-library_search">
        <el-select v-model="relType" class="search-input" :placeholder="$t('common.placeholder.select')" @change="changeRelType" :style="{  marginRight: '12px' }" clearable>
          <el-option v-for="item in faultLibraryOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
        </el-select>
        <el-input class="search-input"  v-model="faultDesc" :placeholder="$t('common.base.search')" prefix-icon="el-icon-search" @change="onChange"> </el-input>
      </div>
      <div class="fault-library_box">
        <div class="fault-library_num">
          <p>
            <el-checkbox 
              :indeterminate="isIndeterminate" 
              v-model="checkAll" 
              @change="handleCheckAllChange">
              {{ selectedFaultLibraryMsg }}
            </el-checkbox>
          </p>
          <p><i class="iconfont icon-info"></i>{{ $t('component.faultLibraryDialog.showTip') }}</p>
        </div>
        <div class="fault-library-tree" v-loading="loading">
            <el-tree 
                ref="tree" 
                :data="faultLibraryList" 
                :check-strictly="true" 
                :default-checked-keys="defaultCheckedKeys" 
                show-checkbox 
                node-key="id" 
                @check="handelCheckChange"
            >
                <div class="custom-tree-node" slot-scope="{ node, data }">
                    <div class="title">
                        <!-- 2 解决节点 -->
                        <span class="icon" v-if="data.faultLabel && data.relType == 0 || data.dataType == 2">
                            {{ data.faultLabel }}
                        </span>
                        <!-- 1 故障节点 -->
                        <span class="icon" v-if="data.relType != 0 && data.dataType == 1">
                            {{ getRealTypeName(data.relType) }}
                        </span>
                        <span class="custom-tree-faultDesc">{{ data.faultDesc }} &nbsp; {{ getComputedStyle(data.relObj || []) }}</span>
                    </div>
                </div>
            </el-tree>
        </div>
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">{{ $t('common.base.cancel') }}</el-button>
      <el-button type="primary" @click="onSubmit">{{ $t('common.base.confirm') }}</el-button>
    </div>
  </base-modal>
</template>
<script>
/** components */
import FaultLibraryHeader from '@src/modules/faultLibrary/components/FaultLibraryHeader.vue';
/** api */
import { librarySelect } from '@src/api/Fault';
/** util */
import { getRootWindow } from '@src/util/dom';

export default {
  name: 'fault-library-dialog',
  props: {
    defaultCheckedKeys: {
      type: Array,
      default: () => ([])
    },
  },
  components: {
    FaultLibraryHeader,
  },
  data() {
    return {
       loading: false,
       defaultProps: {
        label: 'faultDesc',
        disabled: 'disabled'
      },
      isIndeterminate: false,
      isShow: false,
      selectedFaultLibrary: [],
      faultLibraryList: [],
      relType: null, // 关联类型 1：产品  2：物料  3：备件
      faultDesc: '',
      checkAll: false,
    };
  },
  computed: {
    /** 已选择的故障库*/
    selectedFaultLibraryMsg() {
        let checkAllLength = this.selectedFaultLibrary.length;
        return checkAllLength > 0 ? this.$t('component.faultLibraryDialog.haveFaultLibraryTips', { data: checkAllLength}) : this.$t('component.faultLibraryDialog.allCheckbox');
    },
    /** 是否开启云仓灰度*/
    isCloudWarehouse() {
      const RootWindow = getRootWindow(window);
      return RootWindow.grayAuth?.cloudwarehouse || false;
    },
    faultLibraryOptions() {
      let options = [
        {
          label: this.$t('common.base.product'),
          value: 1,
        },
        {
          label: this.$t('common.form.type.material'),
          value: 2,
        },
        {
          label: this.$t('common.base.sparePart'),
          value: 3,
        },
      ];
      return this.isCloudWarehouse ? options.filter(item => item.value != 3) : options.filter(item => item.value != 2);
    },
  },
  methods: {
    
    /** 打开弹窗 */
    openDialog(index) {
        this.faultIndex = index;
        this.isShow = true;

        this.getFaultLibraryData(true);
    },
    /**全选 */
    handleCheckAllChange(val){
        if(val) {
            let allIds = this.faultLibraryList.map(item=>item.id)
            this.$refs.tree.setCheckedKeys(allIds);
            this.selectedFaultLibrary = allIds;
        }else {
            this.resetCheck()
        }
    },
    /**选择故障现象 */
    handelCheckChange() {
        const ids = this.$refs.tree.getCheckedKeys();
        this.selectedFaultLibrary = ids;
        this.formatCheck()
    },
    changeRelType() {
        this.resetCheck()
        this.getFaultLibraryData();
    },
    onChange(){
        // this.resetCheck()
        this.getFaultLibraryData()
    },
    formatCheck() {
        this.isIndeterminate = this.selectedFaultLibrary?.length > 0 && this.selectedFaultLibrary?.length < this.faultLibraryList.length;
        this.checkAll = this.selectedFaultLibrary?.length === this.faultLibraryList.length;
    },
    /** 重置选择 */
    resetCheck() {
        this.selectedFaultLibrary = [];
        this.$refs.tree.setCheckedKeys([]);
        this.isIndeterminate = false;
        this.checkAll = false;
    },
    /** 获取故障树数据 */
    async getFaultLibraryData(initState = false) {
        this.loading = true;
        try {
            const params = {
                relType: this.relType,
                relIdList: [],
                enterState: 1,
                faultDesc: this.faultDesc
            }
            const { success, data = [], message} = await librarySelect({permissionsHide: false, ...params})

            if(!success) return this.$message.warning(message)

            this.faultLibraryList = data;
            if(initState) {
              this.$refs.tree.setCheckedKeys(this.defaultCheckedKeys);
              this.formatCheck()
            }
        
        }catch(error){
            console.log(error)
        } finally{
            this.loading = false;
        }
        

    },
    /** 确认提交 */
    onSubmit() {
      this.$emit('onSubmit', this.selectedFaultLibrary, this.faultIndex);
      this.closeDialog();
    },
    closeDialog() {
      this.isShow = false;
    },
    /** 处理展示标签 */
    getRealTypeName(type) {
      return ['', this.$t('common.base.product'), this.$t('common.form.type.material'), this.$t('common.base.sparePart')][type]
    },
    /** 处理关联产品目录 */
    getComputedStyle(arr = []) {
      if (arr.length == 0) return '';
      return '(' + arr.map(v => v.relObjName).join(',') + ')';
    }
  },
};
</script>
<style lang="scss" scoped>
.fault-library-dialog {
    .fault-library_search {
        margin-bottom: 12px;
        .search-input {
            width: 48.5%;
        }
    }
    .fault-library_box {
        border-radius: 4px;
        border: 1px solid #E8E8E8;
        .fault-library_num{
            display: flex;
            justify-content: space-between;
            height: 40px;
            line-height: 40px;
            background: #FAFAFA;
            border-radius: 4px 4px 0px 0px;
            padding: 0 16px;
            color: #595959;
            p{
                font-size: 14px;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                color: #595959;
            }
            .iconfont{
                margin-right: 5px;
            }
        }
        .fault-library-tree {
            ::v-deep .el-tree-node__content{
                .el-tree-node__expand-icon {
                    padding: 2.5px;
                }
            }
            .custom-tree-node{
                display: flex;
                justify-content: space-between;
                align-items: center;
                width: calc(100% - 28px);
                .title{
                    display: flex;
                    color:#262626;
                    flex:1;
                    @include text-ellipsis();
                    .icon{
                        background: #F4F4F5;
                        border: 1px solid #E9E9EB;
                        line-height: 20px;
                        border-radius: 2px;
                        padding: 0px 8px;
                        margin-right:8px;
                        color: #898989;
                        font-size:12px;
                    }
                }
            }
            .custom-tree-faultDesc {
                display: inline-block;
                width: 450px;
                @include text-ellipsis();
            }
        }
    }

}
</style>
